package graphic.mycomponents;

import filemanager.FileManager;

import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.io.IOException;
import java.util.Iterator;
import java.util.LinkedList;

import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

import core.Function;
import core.Server;
import dbms.DBAddingFunctions;

public class ProgramListPanel extends JPanel {

	String tempProgramName;
	
	public ProgramListPanel()
	{	
		super();
		
		this.populatePanel();
	}
	
	public void populatePanel()
	{
		super.removeAll();
		super.setLayout(new GridBagLayout());
		
		GridBagConstraints c = new GridBagConstraints();
		c.insets = new Insets(5, 10, 5, 10);
		c.fill = GridBagConstraints.BOTH;
		c.anchor = GridBagConstraints.CENTER;
		c.gridy = 0;

		LinkedList<String> users = Function.getProgramNamesList();

		JLabel userId;
		for (Iterator iterator = users.iterator(); iterator.hasNext();)
		{
			c.gridx = 0;
			
			this.tempProgramName = (String) iterator.next();
			
			userId = new JLabel(this.tempProgramName);
			userId.setFont(new Font("Tahoma", Font.BOLD, 20));
			super.add(userId, c);
			
			c.gridx = 1;
			super.add(new OpenDialogButton("delete.jpg", "Remove Program", "Remove Program", this.tempProgramName)
			{
				@Override
				public void actionPerformed(ActionEvent e) {

					int result = JOptionPane.showConfirmDialog(ProgramListPanel.this, "Are you Sure to Remove this Program?\n" +
							"If YES, Server will be restarted too \nso each running process'll be interrupted.", "Remove Program", JOptionPane.OK_CANCEL_OPTION);
					if(result == JOptionPane.OK_OPTION)
					{
						try { Server.getInstance().stopServer(); } catch (IOException exc) {}
						
						DBAddingFunctions.removeProgram((String)this.data);

						FileManager fileManager = Server.getInstance().getPrograms().get((String)this.data);
						fileManager.removeStructure();
						
						ProgramListPanel.this.populatePanel();
						
						Server.getInstance().getPrograms().remove((String)this.data);
						
						Server.getInstance().startServer();
					} else {}
				}	
			}, c);
			
			c.gridy++;
		}
		
		super.revalidate();
		super.repaint();
	}
}